#!/bin/bash

# Mac双系统配置备份恢复脚本
# 用于系统升级前的备份和升级后的恢复

# 设置配置主目录
if [ -z "$CONFIG_HOME" ]; then
  export CONFIG_HOME="${HOME}/.mac_sync"
fi

# 基本目录设置
BACKUP_DIR="/Volumes/Sun/Backups/$(date +%Y%m%d)"
SOURCE_DIR="/Volumes/Sun/AppSettings"
USER_LIBRARY="$HOME/Library"
SYNC_DIR="$CONFIG_HOME"
SCRIPTS_DIR="$SYNC_DIR/scripts"
LOGS_DIR="$SYNC_DIR/logs"

# 日志设置
LOG_FILE="$BACKUP_DIR/backup_log.txt"

# 创建必要目录
mkdir -p "$BACKUP_DIR"
mkdir -p "$BACKUP_DIR/Applications"
mkdir -p "$BACKUP_DIR/Library"
mkdir -p "$SYNC_DIR" "$SCRIPTS_DIR" "$LOGS_DIR"

# 记录日志函数
log_message() {
    echo "[$(date +%Y-%m-%d\ %H:%M:%S)] $1" | tee -a "$LOG_FILE"
}

# 显示菜单
show_menu() {
    clear
    echo "===== Mac双系统配置管理工具 ====="
    echo "1. 系统升级前备份"
    echo "2. 系统升级后恢复"
    echo "3. 查看配置同步状态"
    echo "4. 手动启动应用同步"
    echo "5. 手动启动配置同步"
    echo "6. 优化磁盘空间"
    echo "0. 退出"
    echo "================================"
    echo -n "请选择操作 [0-6]: "
}

# 备份函数
backup_system() {
    log_message "开始系统升级前备份..."
    
    # 1. 备份应用列表
    ls -la /Applications > "$BACKUP_DIR/applications_list.txt"
    log_message "应用列表已备份"
    
    # 2. 备份重要配置文件
    log_message "备份重要配置文件..."
    
    # 可以根据需要添加更多备份项目
    important_configs=(
        "Preferences"
        "Application Support/Adobe"
        "Application Support/Google/Chrome"
        "Application Support/Firefox"
        "Application Support/Visual Studio Code"
        "Application Support/WebStorm"
    )
    
    for config in "${important_configs[@]}"; do
        if [ -d "$USER_LIBRARY/$config" ]; then
            backup_path="$BACKUP_DIR/Library/$config"
            mkdir -p "$(dirname "$backup_path")"
            cp -R "$USER_LIBRARY/$config" "$(dirname "$backup_path")"
            log_message "已备份: $config"
        fi
    done
    
    # 3. 备份启动项
    if [ -d "$USER_LIBRARY/LaunchAgents" ]; then
        mkdir -p "$BACKUP_DIR/Library/LaunchAgents"
        cp "$USER_LIBRARY/LaunchAgents/"*.plist "$BACKUP_DIR/Library/LaunchAgents/"
        log_message "已备份启动项"
    fi
    
    # 4. 备份系统状态信息
    sw_vers > "$BACKUP_DIR/system_version.txt"
    system_profiler SPSoftwareDataType > "$BACKUP_DIR/system_info.txt"
    
    # 5. 备份脚本文件
    mkdir -p "$BACKUP_DIR/.mac_sync/scripts"
    if [ -f "$SCRIPTS_DIR/create_app_links.sh" ]; then
        cp "$SCRIPTS_DIR/create_app_links.sh" "$BACKUP_DIR/.mac_sync/scripts/"
    fi
    
    if [ -f "$SCRIPTS_DIR/sync_app_configs.sh" ]; then
        cp "$SCRIPTS_DIR/sync_app_configs.sh" "$BACKUP_DIR/.mac_sync/scripts/"
    fi
    
    # 备份当前脚本
    cp "$0" "$BACKUP_DIR/.mac_sync/scripts/"
    
    log_message "系统备份完成！备份保存在: $BACKUP_DIR"
    echo "系统备份完成！备份保存在: $BACKUP_DIR"
    echo "按任意键继续..."
    read -n 1
}

# 恢复函数
restore_system() {
    # 列出可用的备份
    echo "可用的备份目录:"
    ls -ld /Volumes/Sun/Backups/*/
    
    echo -n "请输入要恢复的备份目录名称(例如20240517): "
    read backup_date
    
    RESTORE_DIR="/Volumes/Sun/Backups/$backup_date"
    
    if [ ! -d "$RESTORE_DIR" ]; then
        echo "备份目录不存在！"
        echo "按任意键继续..."
        read -n 1
        return
    fi
    
    log_message "开始从 $RESTORE_DIR 恢复系统..."
    
    # 1. 恢复脚本文件
    mkdir -p "$SYNC_DIR/scripts"
    
    if [ -f "$RESTORE_DIR/.mac_sync/scripts/create_app_links.sh" ]; then
        cp "$RESTORE_DIR/.mac_sync/scripts/create_app_links.sh" "$SCRIPTS_DIR/"
        chmod +x "$SCRIPTS_DIR/create_app_links.sh"
        log_message "已恢复应用链接脚本"
    elif [ -f "$RESTORE_DIR/create_app_links.sh" ]; then
        # 兼容旧版备份
        cp "$RESTORE_DIR/create_app_links.sh" "$SCRIPTS_DIR/"
        chmod +x "$SCRIPTS_DIR/create_app_links.sh"
        log_message "已恢复应用链接脚本(旧版路径)"
    fi
    
    if [ -f "$RESTORE_DIR/.mac_sync/scripts/sync_app_configs.sh" ]; then
        cp "$RESTORE_DIR/.mac_sync/scripts/sync_app_configs.sh" "$SCRIPTS_DIR/"
        chmod +x "$SCRIPTS_DIR/sync_app_configs.sh"
        log_message "已恢复配置同步脚本"
    elif [ -f "$RESTORE_DIR/sync_app_configs.sh" ]; then
        # 兼容旧版备份
        cp "$RESTORE_DIR/sync_app_configs.sh" "$SCRIPTS_DIR/"
        chmod +x "$SCRIPTS_DIR/sync_app_configs.sh"
        log_message "已恢复配置同步脚本(旧版路径)"
    fi
    
    # 2. 恢复启动项
    if [ -d "$RESTORE_DIR/Library/LaunchAgents" ]; then
        mkdir -p "$USER_LIBRARY/LaunchAgents"
        cp "$RESTORE_DIR/Library/LaunchAgents/"*.plist "$USER_LIBRARY/LaunchAgents/"
        
        # 更新启动项中的路径
        for plist in "$USER_LIBRARY/LaunchAgents/com.user."*.plist; do
            if [ -f "$plist" ]; then
                # 替换路径引用 - 使用当前用户的脚本路径
                sed -i '' "s|/Users/[^/]*/create_app_links.sh|$SCRIPTS_DIR/create_app_links.sh|g" "$plist"
                sed -i '' "s|/Users/[^/]*/sync_app_configs.sh|$SCRIPTS_DIR/sync_app_configs.sh|g" "$plist"
                sed -i '' "s|/Users/[^/]*/Library/Logs/|$LOGS_DIR/|g" "$plist"
            fi
        done
        
        log_message "已恢复启动项并更新路径"
        
        # 重新加载启动项
        for plist in "$USER_LIBRARY/LaunchAgents/com.user."*.plist; do
            launchctl unload "$plist" 2>/dev/null
            launchctl load -w "$plist"
            log_message "已重新加载启动项: $(basename "$plist")"
        done
    fi
    
    # 3. 运行同步脚本
    if [ -f "$SCRIPTS_DIR/create_app_links.sh" ]; then
        echo "正在运行应用链接同步脚本..."
        bash "$SCRIPTS_DIR/create_app_links.sh"
    fi
    
    if [ -f "$SCRIPTS_DIR/sync_app_configs.sh" ]; then
        echo "正在运行配置同步脚本..."
        bash "$SCRIPTS_DIR/sync_app_configs.sh"
    fi
    
    log_message "系统恢复完成！"
    echo "系统恢复完成！"
    echo "按任意键继续..."
    read -n 1
}

# 查看同步状态
check_sync_status() {
    echo "===== 应用同步状态 ====="
    # 计算共享的应用数量
    shared_apps=$(find /Applications -type l -exec readlink {} \; | grep "/Volumes/Sun/Applications" | wc -l)
    echo "共享应用数量: $shared_apps"
    
    # 计算配置文件链接数量
    config_links=$(find "$USER_LIBRARY" -type l -exec readlink {} \; | grep "/Volumes/Sun/AppSettings" | wc -l)
    echo "配置文件链接数量: $config_links"
    
    # 检查启动项状态
    echo ""
    echo "===== 启动项状态 ====="
    if launchctl list | grep -q "com.user.appsync"; then
        echo "应用同步启动项: 运行中"
    else
        echo "应用同步启动项: 未运行"
    fi
    
    if launchctl list | grep -q "com.user.configsync"; then
        echo "配置同步启动项: 运行中"
    else
        echo "配置同步启动项: 未运行"
    fi
    
    # 显示磁盘使用情况
    echo ""
    echo "===== 磁盘使用情况 ====="
    df -h /Volumes/Sun
    
    # 显示同步脚本状态
    echo ""
    echo "===== 同步脚本状态 ====="
    echo "应用同步脚本: $([ -f "$SCRIPTS_DIR/create_app_links.sh" ] && echo "存在" || echo "不存在")"
    echo "配置同步脚本: $([ -f "$SCRIPTS_DIR/sync_app_configs.sh" ] && echo "存在" || echo "不存在")"
    
    echo ""
    echo "按任意键继续..."
    read -n 1
}

# 优化磁盘空间
optimize_disk() {
    echo "===== 磁盘空间优化 ====="
    echo "当前磁盘使用情况:"
    df -h /Volumes/Sun
    
    echo ""
    echo "开始清理缓存文件..."
    
    # 清理本地系统缓存
    if [ -d "$USER_LIBRARY/Caches" ]; then
        du -sh "$USER_LIBRARY/Caches"
        echo -n "是否清理本地缓存? (y/n): "
        read answer
        
        if [ "$answer" == "y" ]; then
            find "$USER_LIBRARY/Caches" -type f -atime +30 -delete
            echo "已清理30天前的缓存文件"
        fi
    fi
    
    # 清理共享位置上的旧备份
    echo ""
    echo "备份目录使用情况:"
    du -sh /Volumes/Sun/Backups/*
    
    echo -n "是否清理30天前的备份? (y/n): "
    read answer
    
    if [ "$answer" == "y" ]; then
        find /Volumes/Sun/Backups -type d -mtime +30 -exec rm -rf {} \; 2>/dev/null
        echo "已清理30天前的备份"
    fi
    
    # 清理日志文件
    echo ""
    echo "日志目录使用情况:"
    du -sh "$LOGS_DIR"
    
    echo -n "是否清理30天前的日志? (y/n): "
    read answer
    
    if [ "$answer" == "y" ]; then
        find "$LOGS_DIR" -type f -mtime +30 -delete
        echo "已清理30天前的日志文件"
    fi
    
    echo ""
    echo "磁盘优化完成，当前使用情况:"
    df -h /Volumes/Sun
    
    echo ""
    echo "按任意键继续..."
    read -n 1
}

# 主循环
while true; do
    show_menu
    read -n 1 choice
    echo ""
    
    case $choice in
        1)
            backup_system
            ;;
        2)
            restore_system
            ;;
        3)
            check_sync_status
            ;;
        4)
            bash "$SCRIPTS_DIR/create_app_links.sh"
            echo "应用同步完成！按任意键继续..."
            read -n 1
            ;;
        5)
            bash "$SCRIPTS_DIR/sync_app_configs.sh"
            echo "配置同步完成！按任意键继续..."
            read -n 1
            ;;
        6)
            optimize_disk
            ;;
        0)
            echo "感谢使用！再见！"
            exit 0
            ;;
        *)
            echo "无效选择，请重试！"
            sleep 1
            ;;
    esac
done 